import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs';
import { Product } from './product';

@Component({
  selector: 'app-product-component',
  templateUrl: './product-component.component.html',
  styleUrls: ['./product-component.component.css']
})
export class ProductComponentComponent implements OnInit {


  myForm: FormGroup;
  id: AbstractControl;
  productName: AbstractControl;
  price: AbstractControl;
  products$: Observable<Product>;
  currentproduct: Product;
  baseUrl = 'http://127.0.0.1:8080/';
  constructor(private fb: FormBuilder, private httpClient: HttpClient) {
    this.myForm = this.fb.group({
      'productName': [''],
      'price': [''],
      'id': ['']
    });
    this.productName = this.myForm.controls['productName'];
    this.id = this.myForm.controls['id'];
    this.price = this.myForm.controls['price'];
  }


  search() {
    if (this.id.value) {
      this.products$ = <Observable<Product>>this.httpClient.get(this.baseUrl + 'products/' + this.id.value);
    } else {
      this.products$ = <Observable<Product>>this.httpClient.get(this.baseUrl + 'products');
    }
  }

  add() {
    console.log(this.myForm.value);
    this.httpClient.post(this.baseUrl + 'product',
      this.myForm.value).subscribe(
        (val: any) => {
          if (val.succ) {
            this.ngOnInit();
            alert('添加成功!');
          }
        }
      )
  }

  delete() {
    if (!this.currentproduct) {
      alert('必须先选择产品!');
    }
    else {
      this.httpClient.delete(this.baseUrl + 'product/' +
        this.currentproduct.id).subscribe(
          (val: any) => {
            if (val.succ) {
              this.ngOnInit();
              alert('删除成功!');
            }
          }
        )
    }
  }


  select(p: Product) {
    this.currentproduct = p;
    this.myForm.setValue(this.currentproduct);
  }

  update() {
    if (!this.currentproduct) {
      alert('必须先选择用户！');
    } else {
      this.httpClient.put(this.baseUrl + 'product', this.myForm.value).subscribe(
        (val: any) => {
          if (val.succ) {
            this.ngOnInit();
            alert("修改成功");
          }
        }
      );
    }
  }

  ngOnInit(): void {
    this.products$ = <Observable<Product>>this.httpClient.get(this.baseUrl + 'products');
  }

}
